﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OracleClient;
using System.Data;
using NHibernate;
using dbPoll_Application.Helpers;
using NHibernate.Criterion;
using NHibernate.Linq;
using dbPoll_Application.ViewModels;

namespace dbPoll_Application.Models
{
    public class MessageRepository
    {
        public static IDictionary<String, String> GetLatestMessages(int pollID, User recipient)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var messages = (from m in session.Query<Message>()
                            from p in session.Query<Poll>()
                            where m.recipients.Contains(recipient) && p.pollID == pollID && p.messages.Contains(m)
                            orderby m.timeSent descending
                            select m);
            return messages.ToDictionary(m => m.messageID.ToString(), m => m.message);
        }

        public static Boolean UpdateMessage(Message message)
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.SaveOrUpdate(message);
                transaction.Commit();
                return transaction.WasCommitted;
            }
        }
    }
}
